package com.paraz.cst;

/**
 * 
 * Main Looper bean for handling.
 * Version with no async.
 * 
 * @author mparaz
 *
 */
public class SyncCstLooper implements CstLooper<Object> {
	public static final String LINE_TERMINATOR = "\r\n";


	private CstProcessor<Object> cstProcessor;
	
	/**
	 * Running.
	 * 
	 * Volatile will make the change work across different threads.
	 * 
	 */
	private volatile boolean running = true;
	
	public CstProcessor<Object> getCstProcessor() {
		return cstProcessor;
	}

	public void setCstProcessor(CstProcessor<Object> cstProcessor) {
		this.cstProcessor = cstProcessor;
	}

	/**
	 * Loop.
	 */
	public void loop(CstSocket cstSocket) {
		loop(false, cstSocket);
	}
	
	/**
	 * Loop main logic, with a debugging hook.
	 * 
	 * Alternate: Expose a setter for the private API.
	 * 
	 */
	void loop(boolean oneTime, CstSocket cstSocket) {
		final CstInput cstInput = cstSocket.getCstInput();
		final CstOutput cstOutput = cstSocket.getCstOutput();
		while (running) {
			try {
				// Read a String
				final String stringRead = cstInput.read();
		
				// Convert to a request
				final CstProcessorRequest request = CstProcessorRequest.fromString(stringRead);
				
				// Feed to the processor.
				CstProcessorResult result = getCstProcessor().process(request, null, null);
				
				// Return on the same socket.
				cstOutput.write(result.getResult() + LINE_TERMINATOR);
			} catch (CstException e) {
				// Stop running
				break;
			}
			
			// Debugging hook
			if (oneTime) {
				break;
			}
		}
	}
	
	public void stop() {
		running = false;
	}
}
